package com.example.module.main.home.view

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.common.sdk.base.PageEntity
import com.example.module.main.R
import com.example.module.main.home.adapter.HomeArticleAdapter
import com.example.module.main.home.data.mapper.ArticleMapper


class HomeArticleList @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : RecyclerView(context, attrs) {

    private var pageIndex = 0
    private val mAdapter by lazy { HomeArticleAdapter() }
    var onEventListener: OnArticleListEventListener? = null
    override fun onFinishInflate() {
        super.onFinishInflate()
        adapter = mAdapter
        //设置 layoutManager
        layoutManager = LinearLayoutManager(context)
        //设置分割线
        val itemDecoration =DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
        itemDecoration.setDrawable(ColorDrawable(ContextCompat.getColor(context, R.color.main_color_home_article_list_divider)))
        addItemDecoration(itemDecoration)
        // 设置加载更多监听事件
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            loadData()
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        //加载第一页数据
        loadData()
    }

    private fun loadData() {
        pageIndex = pageIndex.plus(1)
        onEventListener?.onLoadDataEvent(pageIndex)
    }

    /**
     * 绑定网络数据，处理分页逻辑
     */
    fun bindData(page: PageEntity<ArticleMapper>?) {
        page?.run {
            if (pageIndex == 0) {
                if (list.isEmpty()) {
                    // TODO: 展示空布局
                } else {
                    mAdapter.setNewInstance(list)
                }
            } else {
                mAdapter.addData(list)
                if (pageIndex > pageCount) {
                    //没有更多数据了
                    mAdapter.loadMoreModule.loadMoreEnd()
                } else {
                    //有下一页数据
                    mAdapter.loadMoreModule.loadMoreComplete()
                }
            }
        }
    }


    /**
     * 加载更多失败
     */
    fun loadMoreFail() {
        mAdapter.loadMoreModule.loadMoreFail()
    }


    /**
     * 通信接口
     */
    interface OnArticleListEventListener {
        fun onLoadDataEvent(currPage: Int)
    }
}